package com.ytf.dogbox.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Outline;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.ytf.dogbox.R;

import java.io.File;



public class ImageFragment extends Fragment {

    //是否可见
    private boolean isVisibleToUser;
    //是否初始化完成
    public boolean isInit = false;
    //全局的view
    private View view;


    ImageView showIv;

    /*
     * 当前页面可见时和不可见的方法
     * */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        setParam();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       //1.创建View视图
        if (view==null){
            view = inflater.inflate(R.layout.fragment_image,container,false);

            isInit=true;
            setParam();
        }

        //2.返回view视图
        return  view ;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("TAG", "onResume: Fragment1-显示数据" );
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e("TAG", "onDestroyView: Fragment1-停止显示" );
        if (showIv!=null){
            Bitmap bitmap=showIv.getDrawingCache();
            if (bitmap!=null && !bitmap.isRecycled()){
                bitmap.recycle();
            }
            Glide.with(this).clear(showIv);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("TAG", "onDestroy: Fragment1-销毁控件" );
    }

    //处理逻辑和网络请求等
    private void setParam() {
        if (isInit && isVisibleToUser && showIv==null) {
            showIv=view.findViewById(R.id.image);
            Log.e("tiwolf", "onCreateView: Fragment1-创建ui" );
            setSurfaceviewCorner(20);
        }
    }

    /**
     * 设置Surfaceviewl圆角
     */
    private void setSurfaceviewCorner(final float radius) {
        showIv.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                Rect rect = new Rect();
                view.getGlobalVisibleRect(rect);
                int leftMargin = 0;
                int topMargin = 0;
                Rect selfRect = new Rect(leftMargin, topMargin, rect.right - rect.left - leftMargin, rect.bottom - rect.top - topMargin);
                outline.setRoundRect(selfRect, radius);
            }
        });
        showIv.setClipToOutline(true);
    }


    int width=100;
    int height=200;
    long time=0;

    public void setShowIv(Bitmap bm){
//       new BitmapWorkerTask().execute(file);
        width=showIv.getWidth();
        height= showIv.getHeight();
        Log.e("TAG", "setShowIv: 图片控件的大小是="+width+";高="+height );
        time=System.currentTimeMillis();
//        Luban.compress(getContext(), file)
//                .setMaxSize(500)                // limit the final image size（unit：Kb）
//                .setMaxHeight(width)             // limit image height
//                .setMaxWidth(height)              // limit image width
//                .putGear(Luban.CUSTOM_GEAR)     // use CUSTOM GEAR compression mode
//                .launch(new OnCompressListener() {
//                    @Override
//                    public void onStart() {
//
//                    }
//
//                    @Override
//                    public void onSuccess(File file) {
//                        Glide.with(ImageFragment.this).load(file)
////                .placeholder(showIv.getDrawable())
//                                .skipMemoryCache(true)
//                                .diskCacheStrategy(DiskCacheStrategy.NONE)
//                                .into(new CustomTarget<Drawable>() {
//                                    @Override
//                                    public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
////                            Log.e("TAG", "onResourceReady: 图片显示" );
//                                        Log.e("TAG", "doInBackground: 1111压缩一张图片所用时间为="+(System.currentTimeMillis()-time));
//                                        showIv.setImageDrawable(drawable);
//                                    }
//
//                                    @Override
//                                    public void onLoadCleared(@Nullable Drawable drawable) {
//                                        Log.e("TAG", "onLoadCleared: 图片清除");
//                                    }
//                                });
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//                });
//        Log.e("TAG", "doInBackground: 6666压缩一张图片所用时间为="+(System.currentTimeMillis()-time));


        //展示缩略图会比较快 在主线程里面跑比子线程里面快。但是容易卡。如果在子线程里面获取流，会很慢
        Log.e("tiwolf", "loadPicture: 展示一张图片的高度为="+height+";宽度为="+width);
        if (width==0 || height==0)return;
        try {
//            ContentResolver resolver=getContext().getContentResolver();
//            Bitmap bm= MediaStore.Images.Media.getBitmap(resolver, Uri.fromFile(file));
//            Bitmap bm= BitmapFactory.decodeFile(file.getPath());
//            Log.i("TAG", "展示一张图片之将文件路径变成图片所用时间为="+(System.currentTimeMillis()-time));
            if (bm.getHeight()<height && bm.getWidth()<width){

            }else{
                double widScale= bm.getWidth()/(width*1.0f);
                double heiScale= bm.getHeight()/(height*1.0f);
                Log.e("TAG", "setShowIv: 展示一张图片 图片的高度="+bm.getHeight()+";图片的宽度="+bm.getWidth()+";高的压缩="+heiScale+";宽的压缩="+widScale);
                if (widScale>heiScale){
                    bm=ThumbnailUtils.extractThumbnail(bm,width,(int) (bm.getHeight()/widScale));
                }else{
                    bm=ThumbnailUtils.extractThumbnail(bm,(int) (bm.getWidth()/heiScale),height);
                }
//                bm= ThumbnailUtils.extractThumbnail(bm,width,height);
            }

            Bitmap bitmap=showIv.getDrawingCache();
            if (bitmap!=null && !bitmap.isRecycled()){
                bitmap.recycle();
            }
            Glide.with(ImageFragment.this).load(bm)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
//                                  Log.e("TAG", "onResourceReady: 图片显示" );
                            Log.i("TAG", "展示一张图片所用时间为="+(System.currentTimeMillis()-time));
                            showIv.setImageDrawable(drawable);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable drawable) {

                            Log.i("TAG", "onLoadCleared: 图片清除");
                        }
                    });
        }catch (Exception e){
            e.printStackTrace();
        }



//        new MyAsyncTask().execute(file);  //todo 使用子线程花费的时间多得多
    }






    class MyAsyncTask extends AsyncTask<File, Integer, Bitmap>
    {
        /**
         * 异步任务：AsyncTask<Params, Progress, Result>:只能子线程发消息到main线程
         * 1.Params:UI线程传过来的参数。可变参数影响asyncTask.execute()和doInBackground().
         * 2.Progress:发送消息的类型。可变参数影响onProgressUpdate()和publishProgress().
         * 3.Result:返回结果的类型。耗时操作doInBackground的返回结果传给执行之后onPostExecute的参数类型。
         *
         * 执行流程：
         * 1.onPreExecute()
         * 2.doInBackground()-->onProgressUpdate()
         * 3.onPostExecute()
         */


        @Override
        protected Bitmap doInBackground(File... files) {
            Log.i("TAG", "setShowIv: 展示一张图片 在后台所需的时间开始="+(System.currentTimeMillis()-time));
            Bitmap bm= null;
            try {
//                ContentResolver resolver=getContext().getContentResolver();
//                bm = MediaStore.Images.Media.getBitmap(resolver, Uri.fromFile(files[0]));
                bm=BitmapFactory.decodeFile(files[0].getPath());

                if (bm.getHeight()<height && bm.getWidth()<width){

                }else{
                    double widScale= bm.getWidth()/(width*1.0f);
                    double heiScale= bm.getHeight()/(height*1.0f);
                    Log.e("TAG", "setShowIv: 展示一张图片 图片的高度="+bm.getHeight()+";图片的宽度="+bm.getWidth()+";高的压缩="+heiScale+";宽的压缩="+widScale);
                    if (widScale>heiScale){
                        bm=ThumbnailUtils.extractThumbnail(bm,width,(int) (bm.getHeight()/widScale));
                    }else{
                        bm=ThumbnailUtils.extractThumbnail(bm,(int) (bm.getWidth()/heiScale),height);
                    }
//                bm= ThumbnailUtils.extractThumbnail(bm,width,height);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.i("TAG", "setShowIv: 展示一张图片 在后台获取流="+(System.currentTimeMillis()-time));
            return bm;
        }

        @Override//实心三角：重写父类方法
        protected void onPreExecute()//执行之前
        {

        }

        @Override
        protected void onPostExecute(Bitmap bitmap)//执行之后
        {
            //在此方法执行main线程操作
            if (bitmap!=null){
                Glide.with(ImageFragment.this).load(bitmap)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(new CustomTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
//                                  Log.e("TAG", "onResourceReady: 图片显示" );
                                Log.i("TAG", "展示一张图片所用时间为="+(System.currentTimeMillis()-time));
                                showIv.setImageDrawable(drawable);
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable drawable) {

                                Log.i("TAG", "onLoadCleared: 图片清除");
                            }
                        });
            }
        }
    }

}
